package dhadi.model;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import dhadi.util.Util;

public class Node {
	
	public final String name;
	public Pick pick;
	private List<Edge> edges;
	private List<Node> adjusantNodes;
	private Board board;
	
	public Node(String name, Board board)
	{
		this.name = name;
		this.board = board;
	}
	
	public String getName() {
		return this.name;
	}
	
	public boolean isNodeEmpty()
	{
		return pick == null;
	}
	
	public boolean isCornerNode() {
	    return board.getCornerNodes().contains(this.name);
	}
	
	public void placePick(Pick pick) {
		if (this.isNodeEmpty()) {
			this.pick = pick;
		}
	}
	
	public void releasePick(Pick pick) {
		if (this.pick != null && this.pick.equals(pick)) {
			this.pick = null;
		}
	}
	
	public List<Node> getAdjusantNodes() {
		if (this.adjusantNodes == null)
		{
			this.adjusantNodes = new ArrayList<Node>(2);
			for (Edge e : this.edges)
			{
				if (!this.equals(e.getNodeA()))
					this.adjusantNodes.add(e.getNodeA());
				
				if (!this.equals(e.getNodeB()))
					this.adjusantNodes.add(e.getNodeB());
			}
			this.adjusantNodes.add(this);
		}
		return this.adjusantNodes;		
	}
	
	public boolean isAdjacent(Node node) {
	    return this.adjusantNodes.contains(node);
	}
	
	public List<Node> getAdjusantEmptyNodes() {
		List<Node> adjusantEmtpyNodes = new ArrayList<Node>();
		for (Node n : this.getAdjusantNodes())
		{
			if (n.isNodeEmpty())
				adjusantEmtpyNodes.add(n);
		}
		return adjusantEmtpyNodes;
	}
	
	public List<Edge> getEdges()
	{
		return this.edges;
	}
	
	public void setEdges(List<Edge> edges)
	{
		this.edges = edges;		
	}
	
	@Override
	public String toString() {
		return "Node [name=" + name + ", pick=" + pick + "]";
	}

	public JSONObject toJson() throws JSONException {
		JSONObject json = new JSONObject();
		json.put("Name", this.name);
		json.put("Pick", this.pick==null?"null":this.pick.toJson());
		return json;
	}	
	
	public static Node fromJson(String jsonString, SerializationContext context) 
	throws JSONException {
	    if (Util.isEmptyJson(jsonString)) return null;	    
	    JSONObject json = new JSONObject(jsonString);
	    Node node;
	    node = context.board.findNodeByName(json.getString("Name"));
	    if (context.isLoadingMoves) {
	        node.pick = null;	        	        	        	        
	    } else {
	        throw new IllegalArgumentException("unsupported context, Could not set pick to a node");
	    }
	    return node;
	}
}
